package net.csdn.business.kanban.feign.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import net.csdn.business.kanban.common.constant.CommonConstants;
import net.csdn.business.kanban.common.utils.TokenUtil;
import net.csdn.business.kanban.feign.config.properties.FeignAuthProperties;
import org.springframework.core.Ordered;
import org.springframework.util.CollectionUtils;

import java.util.Collection;

/**
 * @Desc:
 * @ClassName: AliFeignClientInterceptor
 * @Author: zhangyl
 * @Date: 2022/12/21 10:02
 */

@Data
@RequiredArgsConstructor
public class AuthFeignClientInterceptor implements RequestInterceptor, Ordered {

    private final FeignAuthProperties feignAuthConfig;

    @Override
    public int getOrder() {
        return CommonConstants.INT_ONE;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // fix 云效openApi 携带External-token导致的鉴权错误
        Collection<String> noFills = requestTemplate.headers().get(CommonConstants.HEADER_TOKEN_EXTERNAL_NO_FILL);
        if (!CollectionUtils.isEmpty(noFills)) {
            requestTemplate.removeHeader(CommonConstants.HEADER_TOKEN_EXTERNAL_NO_FILL);
            if (noFills.contains(CommonConstants.TRUE)) {
                return;
            }
        }
        requestTemplate.header(CommonConstants.HEADER_TOKEN_EXTERNAL_AK, feignAuthConfig.getAk());
        requestTemplate.header(CommonConstants.HEADER_TOKEN_EXTERNAL_TOKEN, TokenUtil.generateToken(feignAuthConfig.getAk(), feignAuthConfig.getSk()));
    }
}